package com.sluggard.ai.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sluggard.ai.manage.VectorStoreManage;
import com.sluggard.ai.mapper.KnowledgeFileMapper;
import com.sluggard.ai.model.entity.KnowledgeFileEntity;
import com.sluggard.ai.service.IKnowledgeFileService;
import com.sluggard.common.exception.BusinessException;
import org.springframework.ai.document.Document;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 知识库文件服务实现类
 *
 * @author lizheng
 * @since 2025-04-23
 */
@Service
public class KnowledgeFileServiceImpl extends ServiceImpl<KnowledgeFileMapper, KnowledgeFileEntity> implements IKnowledgeFileService {

    private static final String UPLOAD_PATH = "/Users/apple/data/file/";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Autowired
    @Qualifier("ioTaskExecutor")
    private ThreadPoolTaskExecutor ioTaskExecutor;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upload(MultipartFile file, Long knowledgeId) {
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }

        // 生成文件存储路径
        String originalFilename = file.getOriginalFilename();
        String fileType = getFileType(originalFilename);
        String datePath = LocalDateTime.now().format(DATE_FORMATTER);
        String newFileName = UUID.randomUUID() + "." + fileType;
        String filePath = UPLOAD_PATH + datePath + "/" + newFileName;

        // 创建目录
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            if (!dest.exists()) {
                dest.createNewFile();
            }
            // 保存文件
            file.transferTo(dest);

            // 保存文件信息
            KnowledgeFileEntity entity = new KnowledgeFileEntity();
            entity.setName(originalFilename);
            entity.setFileType(fileType.toUpperCase());
            entity.setFilePath(filePath);
            entity.setSource("上传");
            entity.setSliceCount(0);
            entity.setHitCount(0);
            entity.setKnowledgeId(knowledgeId);
            save(entity);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public void splitFile(Long id) {
        KnowledgeFileEntity knowledgeFileEntity = getById(id);
        if (knowledgeFileEntity == null) {
            throw new BusinessException("文件不存在");
        }
        knowledgeFileEntity.setSliceResult(1);
        updateById(knowledgeFileEntity);
        ioTaskExecutor.execute(() -> {
            File file = new File(knowledgeFileEntity.getFilePath());
            if (!file.exists()) {
                knowledgeFileEntity.setSliceResult(3);
                updateById(knowledgeFileEntity);
                throw new BusinessException("文件不存在");
            }
            try {
                BufferedReader fileReader = new BufferedReader(new FileReader(file));
                String line;
                List<Document> documents = new ArrayList<>();
                StringBuffer sb = new StringBuffer();
                while ((line = fileReader.readLine()) != null) {
                    sb.append(line);
                    if(line.contains("\n")){
                        documents.add(new Document(sb.toString()));
                        sb.setLength(0);
                    }
                    if(documents.size() == 500) {
                        TokenTextSplitter tokenTextSplitter = new TokenTextSplitter(500,50,50,100,true);
                        tokenTextSplitter.split(documents);
                        VectorStore vectorStore = VectorStoreManage.getVectorStore(knowledgeFileEntity.getKnowledgeId());
                        vectorStore.add(documents);
                        documents.clear();
                    }
                }

                knowledgeFileEntity.setSliceResult(2);
                updateById(knowledgeFileEntity);
            } catch (Exception e) {
                log.error("文件切分失败", e);
                knowledgeFileEntity.setSliceResult(3);
                updateById(knowledgeFileEntity);
            }
        });

    }

    /**
     * 获取文件类型
     */
    private String getFileType(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            throw new BusinessException("文件格式不正确");
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }
}